﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using YogaDictionary.Common;
using YogaDictionary.Model;

namespace YogaDictionary.ViewModel
{
    public class ViewModelMain : ViewModelBase
    {
        public RelayCommand<Word> ShowNewDefinitionCommand { get; private set; }

        public List<Word> AllWords
        {
            get { return DataRepo.Words; }
        }

        private Word _selectedWord;
        private bool UpdateSelectedWord(Word newWord)
        {
            if (_selectedWord == newWord)
                return false;

            _selectedWord = newWord;
            RaisePropertyChanged("SelectedWord");
            return true;
        }

        public Word SelectedWord
        {
            get { return _selectedWord; }
            set
            {
                if (UpdateSelectedWord(value))
                    Search = value.Value;
            }
        }

        private string _search = string.Empty;
        public string Search
        {
            get { return _search; }
            set
            {
                if (_search == value)
                    return;

                _search = value;
                RaisePropertyChanged("Search");
                
                UpdateSelectedWord(AllWords.FirstOrDefault(w => w.Value.ToLower().StartsWith(_search.ToLower())));
            }
        }

        public ViewModelMain()
        {
            ShowNewDefinitionCommand = new RelayCommand<Word>(ViewModelWindowsManager.ShowNewDefinitionWindow);

            var word = AllWords.FirstOrDefault();
            if (word != null)
                SelectedWord = word;
        }

    }
}